extends Node2D

@export var card_info:CardData
@export var is_save_card := false
@onready var v_box_container: VBoxContainer = $Sprite2D/VBoxContainer
@onready var texture_rect: TextureRect = $Sprite2D/TextureRect
@onready var label: Label = $Sprite2D/Label

var gem_cost_res = preload("res://scenes/card/gemCost.tscn")
var idx:int
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	GameManager.card_reset_signal.connect(reset)
	pass # Replace with function body.

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	pass
	
@onready var label_2: Label = $Sprite2D/Label2
func initialize(data: CardData , pos):
	card_info = data
	idx = pos
	update_display()
	if card_info.card_type == 1:
		label_2.show()
		texture_rect.hide()

func update_display():
	# 根据card_data更新场景中的显示元素
	# 更新其他UI元素...
	if !is_node_ready():
		await ready
	texture_rect.texture = Globals.gem_img[card_info.bonus_color]
	label.text = str(card_info.prestige)
	for key in card_info.cost:
		if card_info.cost[key] > 0:
			var gem_ini = gem_cost_res.instantiate()
			gem_ini.init(key,card_info.cost[key])
			v_box_container.add_child(gem_ini)

@onready var animated_sprite_2d: AnimatedSprite2D = $Sprite2D/AnimatedSprite2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
func _on_area_2d_mouse_entered() -> void:
	if card_info.card_type == 1:
		return
	animation_player.play('hover')

func _on_area_2d_mouse_exited() -> void:
	animation_player.play('RESET')

func _on_area_2d_input_event(viewport: Node, event: InputEvent, shape_idx: int) -> void:
	get_viewport().set_input_as_handled()
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			if card_info.card_type == 1:
				return
			if GameManager.current_player != 0:
				return
			GameManager.select_card = self
			GameManager.card_reset_signal.emit()
			GameManager.update_opt_button.emit()
			animated_sprite_2d.play('default')
			animated_sprite_2d.show()
			get_viewport().set_input_as_handled()
			
func reset():
	if self != GameManager.select_card:
		animated_sprite_2d.hide()
		
func close_anim():
	animated_sprite_2d.hide()
	success.hide()
	
@onready var success: AnimatedSprite2D = $Sprite2D/success
func can_buy():
	success.show()
	
